/*
 * @lc app=leetcode id=110 lang=cpp
 *
 * [110] Balanced Binary Tree
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        int h = 0;
        if (!root) {
            return true;
        }

        return isBalanced(root, h);
    }

    bool isBalanced(TreeNode* root, int &h) {
        if (!root) {
            h = 0;
            return true;
        }

        int hl, hr;
        if (isBalanced(root->left, hl) && isBalanced(root->right, hr)) {
            if (hl-hr>1 || hr-hl>1) {
                h = -1;
            } else {
                h = max(hl,hr) + 1;
            }
        } else {
            h = -1;
        }
        return h>=0;
    }
};

